package org.example.erp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.erp.controller.DataResult;
import org.example.erp.domain.SysUser;
import org.example.erp.domain.SysUserDept;
import org.example.erp.domain.SysUserPost;
import org.example.erp.domain.SysUserRole;
import org.example.erp.mapper.SysUserDeptMapper;
import org.example.erp.mapper.SysUserPostMapper;
import org.example.erp.mapper.SysUserRoleMapper;
import org.example.erp.service.SysUserService;
import org.example.erp.mapper.SysUserMapper;
import org.example.erp.web.DTO.UserDTO;
import org.example.erp.web.VO.UserPostsRolesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 28254
 * @description 针对表【sys_user(用户表)】的数据库操作Service实现
 * @createDate 2024-10-07 18:51:18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder bcrypt;

    @Autowired
    private SysPostServiceImpl postService;
    @Autowired
    private SysRoleServiceImpl roleService;
    @Autowired
    private SysUserPostMapper userPostMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysUserDeptMapper userDeptMapper;

    //查询用户和所属部门信息

    public IPage<SysUser> findUserByDept(Integer currentPage, Integer pageSize, String username,
                                         String phone, String status, String startTime, String endTime, Integer deptId) {
        Page<SysUser> page = new Page<>(currentPage, pageSize);
        List<Integer> deptList = new ArrayList<>();
        if (deptId != null) {
            deptList = sysUserMapper.findDeptList(deptId);
            deptList.add(deptId);
            return sysUserMapper.findUserByDept(page, username, phone, status, startTime, endTime, deptList);
        }
        return sysUserMapper.findUserByDept(page, username, phone, status, startTime, endTime, deptList);
    }

    // 删除用户信息
    public void deleteUserByIds(List<Integer> userIds) {
        sysUserMapper.deleteUserByIds(userIds);
    }


    //新增用户信息
    public DataResult insertUser(UserDTO userDTO) {
        SysUser sysUser = userDTO.getUser();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", sysUser.getUserName());
        if (this.exists(queryWrapper)) {
            return DataResult.error("已经存在该用户，添加失败!");
        }
        sysUser.setPassword(bcrypt.encode(sysUser.getPassword()));
        this.save(sysUser); //添加用户
        Integer userId = sysUser.getUserId(); //添加成功获取主键ID
        Integer deptId = sysUser.getDeptId(); //添加成功获取部门Id
        sysUserMapper.insertPost(userId, userDTO.getPostIds()); //添加岗位关联表
        sysUserMapper.insertRole(userId, userDTO.getRoleIds()); //添加角色关联表
        sysUserMapper.insertDept(userId, deptId); //添加部门关联表
        return DataResult.success();
    }

    // 根据ID查询用户信息
    public UserPostsRolesVO findUserById(Integer userId) {
        UserPostsRolesVO vo = new UserPostsRolesVO();
        QueryWrapper<SysUserPost> queryWrapperPost = new QueryWrapper<>();
        queryWrapperPost.select("post_id")
                .eq("user_id", userId);
        vo.setOwnPostIds(userPostMapper.selectObjs(queryWrapperPost));
        QueryWrapper<SysUserRole> queryWrapperRole = new QueryWrapper<>();
        queryWrapperRole.select("role_id")
                .eq("user_id", userId);
        vo.setOwnRoleIds(userRoleMapper.selectObjs(queryWrapperRole));
        vo.setSysUser(sysUserMapper.findUserById(userId));
        vo.setPostIds(postService.list());
        vo.setRoleIds(roleService.list());
        return vo;
    }

    // 修改用户信息
    public void updateUser(UserDTO userDTO) {
        SysUser sysUser = userDTO.getUser();
        this.updateById(sysUser);
        userRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getUserId())); //删除角色关联
        userPostMapper.delete(new QueryWrapper<SysUserPost>().eq("user_id", sysUser.getUserId())); //删除岗位关联
        userDeptMapper.delete(new QueryWrapper<SysUserDept>().eq("user_id",sysUser.getUserId()));//删除部门关联
        List<Integer> postIds = userDTO.getPostIds();
        List<Integer> roleIds = userDTO.getRoleIds();
        Integer deptId = sysUser.getDeptId();
        if (!postIds.isEmpty()) sysUserMapper.insertPost(sysUser.getUserId(), postIds); //添加岗位关联表
        if (!roleIds.isEmpty()) sysUserMapper.insertRole(sysUser.getUserId(), roleIds); //添加角色关联表
        if (deptId!=null) sysUserMapper.insertDept(sysUser.getUserId(), deptId); //添加部门关联表
    }

    //查询已经授权角色的用户
    public Page<SysUser> findSelectUser(IPage<SysUser> page, Integer roleId, String username, String phone) {
        return baseMapper.findSelectUser(page,roleId,username,phone);
    }
}




